from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from app.models import Check_info
# Create your views here.


def index(request):
    return render(request, 'index.html')


def show_qr(request):
    name = request.POST.get('name')
    uid = request.POST.get('uid')
    print('request.body：', request.body)
    # import json
    # body = request.body.decode('utf8')
    # info = json.loads(body)
    # print(info)
    context = {
        'name': name,
        'uid': uid,
        'url': f'http://127.0.0.1:8000/check_info?name={name}&uid={uid}',
    }
    return render(request, 'qr_code.html', context=context)


def check_info(request):
    name = request.GET.get('name')
    uid = request.GET.get('uid')
    check_info1 = Check_info.objects.create(name=name, uid=uid)
    check_info1.save()
    message = f'用户{name}-{uid}签到成功！'
    return HttpResponse(message)


def get_result(request):
    id = request.GET.get('id')
    if id:
        result = Check_info.objects.filter(id=id)
    else:
        result = Check_info.objects.all()
    if result:
        result_dict = {
            'code': 200,
            'message': 'success',
            'data': [{'id': x.id, 'uid': x.uid, 'name': x.name, 'time': x.check_time} for x in result]
        }
    else:
        result_dict = {
            'code': 404,
            'message': 'not exist',
            'data': [],
        }
    return JsonResponse(result_dict,  json_dumps_params={'ensure_ascii': False})

